#!/usr/bin/env bash

alias art="php artisan"
__art()
{
  local cur prev opts _opts_base="list migrate"

  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  # prev="${COMP_WORDS[COMP_CWORD-1]}"
  if [[ -e artisan ]]; then
    opts="$_opts_base $(php artisan | grep -P ':\w' | awk '{print $1}' | xargs)"
  else
    opts="$_opts_base
    api:generate api:update app:name
    auth:clear-resets cache:clear cache:forget cache:table config:cache config:clear
    make:auth make:command make:controller make:event make:exception make:factory make:job make:listener make:mail make:middleware
    make:migration make:model make:notification make:policy make:provider make:request make:resource make:rule make:seeder make:test
    migrate:fresh migrate:install migrate:refresh migrate:reset migrate:rollback migrate:status
    notifications:table package:discover
    queue:failed queue:failed-table queue:flush queue:forget queue:listen queue:restart queue:retry queue:table queue:work
    route:cache route:clear route:list
    db:seed event:generate key:generate
    schedule:run session:table storage:link vendor:publish view:clear"
  fi

  _get_comp_words_by_ref -n : cur
  COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
  __ltrim_colon_completions "$cur"
}
complete -F __art art
alias artm="php artisan migrate"
alias artms="php artisan migrate:status"
alias artmr="php artisan migrate:rollback"
alias artml="php artisan make:migration --path database/migrations/local_recreate"

function aam() {
  art admin:make --model "App\\Admin\\Models\\$1" "${2-$1}Controller"
}
__aam()
{
  local cur prev opts _git_root

  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  _git_root=$(git rev-parse --show-toplevel)
  if ! [[ "$_git_root" ]]; then
    return
  fi
  # prev="${COMP_WORDS[COMP_CWORD-1]}"
  if [[ -d "$_git_root/app/Admin/Models" ]]; then
    opts="$(ls $_git_root/app/Admin/Models/*.php | xargs -i basename {} | sed 's/\.php//g')"
  else
    return
  fi

  _get_comp_words_by_ref -n : cur
  COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
  __ltrim_colon_completions "$cur"
}
complete -F __aam aam
function artds() {
  php artisan db:seed --class=$1
}
__artds()
{
  local cur prev opts _git_root _dir

  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  _git_root=$(git rev-parse --show-toplevel)
  if ! [[ "$_git_root" ]]; then
    return
  fi
  # prev="${COMP_WORDS[COMP_CWORD-1]}"
  _dir="$_git_root/database/seeds/"
  if [[ -d "$_dir" ]]; then
    opts="$(ls $_dir/*.php | xargs -i basename {} | sed 's/\.php//g')"
  else
    return
  fi

  _get_comp_words_by_ref -n : cur
  COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
  __ltrim_colon_completions "$cur"
}
complete -F __artds artds
alias db:reset="php artisan migrate:reset && php artisan migrate --seed"
